import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TCPClient {
    private Socket socket = null;
    private String serverIp;
    private int serverPort;
    //构建客户端
    public TCPClient(String serverIp,int serverPort) throws IOException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        this.socket = new Socket(serverIp,serverPort);
    }
    private void start(){
        Scanner scanner = new Scanner(System.in);
            try (InputStream inputStream = socket.getInputStream();
                 OutputStream outputStream = socket.getOutputStream()){
                //客户端发送请求
                while (true) {
                    System.out.println("请输入请求指令->");
                    String request = scanner.next();
                    if (request.equals("exit")) {
                        System.out.println("程序退出");
                        break;
                    }
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(request);
                    printWriter.flush();
                    //接受服务器响应
                    Scanner scannerResponse = new Scanner(inputStream);
                    String response = scannerResponse.next();
                    String log = String.format("%s,%s", request, response);
                    System.out.println(log);
                }
            }catch (IOException e){
                e.printStackTrace();
            }
    }

    public static void main(String[] args) throws IOException {
        TCPClient tcpClient = new TCPClient("127.0.0.1",9999);
        tcpClient.start();
    }
}
